import axios from 'axios';
import qs from 'qs';

const baseUrl = 'http://39.105.98.166:8008/api';

const http = axios.create({
	// baseURL: baseUrl,
	timeout: 30000,
	transformRequest: [
		function(data) {
			return JSON.stringify(data);
		}
	]
});

// http request 拦截器
http.interceptors.request.use(
	(config) => {
		config.headers = {
			'Content-Type': 'application/json;',
			'Authorization': 'aaa'
		};
		return config;
	},
	(err) => {
		return Promise.reject(err);
	}
);

// http response 拦截器
http.interceptors.response.use(
	(response) => {
		if (response.status < 400) {
			if (response.data.code === 0 || response.data.status === 200) {
				return Promise.resolve(response.data);
			}
			if (response.data.code === 302) {
				const root = response.data.result.indexOf('http://') === -1 ? 'http://' : '';
				setTimeout(() => {
					window.location.href = `${root}${response.data.result}?serverName=${encodeURIComponent(
                        window.btoa(window.location.href.split('?')[0])
                    )}`;
				}, 300);
			}
			return Promise.reject(response.data);
		}
		return Promise.reject();
	},
	() => {
		return Promise.reject();
	}
);
const formDataHttp = axios.create({
	// baseURL: baseUrl,
	timeout: 30000,
	transformRequest: [
		function(data) {
			return qs.stringify(data);
		}
	]
});

// http request 拦截器
formDataHttp.interceptors.request.use(
	(config) => {
		config.headers = {
			'Content-Type': 'application/x-www-form-urlencoded'
		};
		return config;
	},
	(err) => {
		return Promise.reject(err);
	}
);

// http response 拦截器
formDataHttp.interceptors.response.use(
	(response) => {
		if (response.status < 400) {
			if (response.data.code === 0 || response.data.status === 0) {
				return Promise.resolve(response.data);
			}
			if (response.data.code === 302) {
				const root = response.data.result.indexOf('http://') === -1 ? 'http://' : '';
				setTimeout(() => {
					window.location.href = `${root}${response.data.result}?serverName=${encodeURIComponent(
                        window.btoa(window.location.href.split('?')[0])
                    )}`;
				}, 300);
			}
			return Promise.reject(response.data);
		}
		return Promise.reject();
	},
	() => {
		return Promise.reject();
	}
);
export {
	baseUrl,
	http,
	formDataHttp
};